import { useEffect, useRef, useState } from 'react';

export default function useCountDown() {
  let timer = useRef();
  const [count, setCount] = useState();

  const start = currentCount => {
    setCount(currentCount);
    timer.current && clearInterval(timer.current);
    timer.current = setInterval(() => {
      setCount(count => count-1)
    }, 1000);
  };

  const stop = () => {
    timer.current && clearInterval(timer.current);
  };

  useEffect(() => {
    return () => {
      clearInterval(timer.current);
    };
  }, [timer]);

  return {
    count,
    start,
    stop,
  };
};
